package day_2022_7_to_8.day48;

import java.util.ArrayList;
import java.util.List;

/**
 * @author haomin
 * @date 2022/08/25 23:09
 **/
public class Day40_1_Num658_FindClosestElements {
    public static void main(String[] args) {
        //[0,1,1,1,2,3,6,7,8,9]
        //9
        //4
        List<Integer> closestElements = findClosestElements(new int[]{0,1,1,1,2,3,6,7,8,9}, 9, 4);
        for (Integer closestElement : closestElements) {
            System.out.print(closestElement+" ");
        }
    }

    class Solution {
        public List<Integer> findClosestElements(int[] arr, int k, int x) {
            //滑动窗口
            int left = 0;
            for(int i = 0; i < arr.length; i++){
                int gap = Math.abs(arr[i]-x);
                while (i-left >= k && gap < Math.abs(arr[left]-x)){
                    left++;
                }
            }
            List<Integer> list = new ArrayList<>();
            for (int i = left; i < left + k; i++){
                list.add(arr[i]);
            }
            return list;
        }
    }

    public static List<Integer> findClosestElements(int[] arr, int k, int x) {
        List<Integer> res = new ArrayList<>();
        int[] ans = new int[k];
        int min = Integer.MAX_VALUE;
        for(int i = 0; i <= arr.length-k;++i){
            int sum = 0, index = i, count = k;
            while(count-- > 0) sum = sum + arr[index++] - x;
            System.out.println(sum);
            sum = Math.abs(sum);
            if(min > sum) {
                min = sum;
                index = i;count = 0;
                while(count < k) {
                    ans[count] = arr[index];
                    count++;index++;
                }
            }
        }
        for (int an : ans) {
            res.add(an);
        }
        return res;
    }

}